#include "serialworks.h"
#include <QDebug>
#include<QMessageBox>
Serialworks::Serialworks(QObject *parent):
     QThread(parent)
{
    m_port = new QSerialPort(this);
}

Serialworks::~Serialworks()
{

}

void Serialworks::run()
{
    QByteArray recvdata;
    while(m_comFd){
        if(m_port->bytesAvailable()){
            recvdata = m_port->readAll();
            if(recvdata.length()>0){
               emit signal_show_recv_com_data(recvdata);
            }
        }
        usleep(1000);
    }
}

void Serialworks::slot_com_param(QString com, int bitrate,int parity)
{
    if(this->isRunning()){
        this->closeCom();
        if(!openCom(com,bitrate,parity)){
            emit signal_show_warning();
            return ;
        }
        start();
    }
    else
    {
        m_comName = com;
        m_bitrate = bitrate;
        m_parity = parity;
    }
}

bool Serialworks::openCom(QString com,int bitrate,int parity)
{
    m_comName = com;
    m_bitrate = bitrate;
    m_parity = parity;

    m_port->setPortName(m_comName);
    m_comFd = m_port->open(QIODevice::ReadWrite);
    if(!m_comFd){
        qDebug() << "serial Port open error\n";
        return false;
    }


    switch(bitrate){
    case 4800: m_port->setBaudRate(QSerialPort::Baud4800);break;
    case 9600: m_port->setBaudRate(QSerialPort::Baud9600);break;
    case 19200:m_port->setBaudRate(QSerialPort::Baud19200);break;
    case 38400:m_port->setBaudRate(QSerialPort::Baud38400);break;
    case 57600:m_port->setBaudRate(QSerialPort::Baud57600);break;
    case 115200:m_port->setBaudRate(QSerialPort::Baud115200);break;
    default:
        m_port->setBaudRate(QSerialPort::Baud115200);
    }

    switch (m_parity) {
    case 0: m_port->setParity(QSerialPort::NoParity);break;
    case 1: m_port->setParity(QSerialPort::OddParity);break;
    case 2: m_port->setParity(QSerialPort::EvenParity);break;
    default:
        m_port->setParity(QSerialPort::NoParity);
    }

    m_port->setDataBits(QSerialPort::Data8);
    m_port->setStopBits(QSerialPort::OneStop);
    m_port->setFlowControl(QSerialPort::NoFlowControl);

    return true;
}

void  Serialworks::closeCom()
{
    m_port->close();
    m_comFd=0;
}

void Serialworks::writeCom(QString str)
{
    m_port->write(str.toLatin1().data(),str.length());
    m_port->waitForBytesWritten(10);
}

void Serialworks::writeCom(char *p, int len)
{
    m_port->write(p,len);
    m_port->waitForBytesWritten(10);
}


